package filter;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {
	private String [] pathList;
    public LoginFilter() {
        
    }

	public void destroy() { }
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hreq = (HttpServletRequest)request;
		HttpServletResponse hresp = (HttpServletResponse)response;
		String requestPath = hreq.getServletPath();
		HttpSession session = hreq.getSession();
		System.out.println(requestPath);
		if(contaisPath(requestPath)){
			chain.doFilter(request, response);
		}else if(session.getAttribute("user")==null){
			hresp.sendRedirect("/JSP_SQL/jsp/login.jsp");
		}else{
			chain.doFilter(request, response);
		}
	}

	public boolean contaisPath(String path) {
		for(String p:pathList){
			if(p.equals(path)){
				return true;
			}	
		}
		return false;
	}

	public void init(FilterConfig fConfig) throws ServletException {
		String values = fConfig.getInitParameter("paths");
		pathList = values.split(",");
	}
}
